package com.gang.lingdian.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author gyg
 * @version 1.0
 * @date 2021/10/31 上午10:41
 * @Description:
 */

//第一步 创建资源类，定义属性和操作方法
class Share{
    private int num = 0;
    // 创建Lock
    Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    //+1
    public void incr() throws InterruptedException {
        // 上锁
        lock.lock();
        try {
            //判断
            while (num != 0){
                condition.await();
            }
            // 干活
            num++;
            System.out.println(Thread.currentThread().getName()+"::"+num);
            // 通知
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }

    // -1
    public void decr() throws InterruptedException {
        //上锁
        lock.lock();
        try {
            // 判断
            while (num != 1){
                condition.await();
            }
            num--;
            System.out.println(Thread.currentThread().getName()+"::"+num);
            condition.signalAll();
        }finally {
            lock.unlock();
        }
    }


}

public class ThreadDemo2 {

    public static void main(String[] args) {
        Share share = new Share();
        new Thread(()->{
            for (int i = 0; i <10; i++) {
                try {
                    share.incr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        },"AA").start();
        new Thread(()->{
            for (int i = 0; i <10; i++) {
                try {
                    share.decr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"BB").start();
        new Thread(()->{
            for (int i = 0; i <10; i++) {
                try {
                    share.incr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"CC").start();

        new Thread(()->{
            for (int i = 0; i <10; i++) {
                try {
                    share.decr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"DD").start();
    }

}
